package cc.mrbird.febs.weixin.OAuth2;

import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.customer.entity.Customer;
import cc.mrbird.febs.customer.service.ICustomerService;
import cc.mrbird.febs.weixin.WeiXinConstant;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;

/**
 * Created with IntelliJ IDEA.
 *
 * @ Auther: 马超伟
 * @ Date: 2020/06/05/11:30
 * @ Description: 微信授权登录处理工作类
 * @author Administrator
 */
@CrossOrigin
@Controller
@RequestMapping("/api/weiXin")
public class WeiXinLoginApiController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private ICustomerService customerService;
    /**
     * @ Description: 请求微信登录的token
     * @ Param: [request, response]
     * @ return: java.lang.String
     * @ Author: 马超伟
     * @ Date: 2020/6/10
     * 页面进入首页调这个接口
     */
    @CrossOrigin
    @RequestMapping(value = "/getCode",method = RequestMethod.GET)
    @ResponseBody
    public FebsResponse getCode(HttpServletRequest request, HttpServletResponse response,String url) throws IOException {
        //拼接urlvalue =
        request.getSession().setAttribute("url", url);
        StringBuilder stringBuilderUrl = new StringBuilder();
        stringBuilderUrl.append("https://open.weixin.qq.com/connect/oauth2/authorize?");
        //appid
        stringBuilderUrl.append("appid=" + WeiXinConstant.AppId);
        //转码
        try {
            //回调地址 ,回调地址要进行Encode转码
            String redirect_uri = URLEncoder.encode(WeiXinConstant.REDIRECT_URI, "utf-8");
            stringBuilderUrl.append("&redirect_uri=" + redirect_uri);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        stringBuilderUrl.append("&response_type=code");
        stringBuilderUrl.append("&scope=snsapi_userinfo");
        stringBuilderUrl.append("&state=" + request.getSession().getId());
        stringBuilderUrl.append("&connect_redirect=1#wechat_redirect");
//        return "redirect:" + url.toString();
//        response.sendRedirect(url.toString());
        return new FebsResponse().success().put("url", stringBuilderUrl.toString());
    }

    @RequestMapping(value ="/callback")
    public void callback(String code, String state, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (StringUtils.isNotEmpty(code)) {
            StringBuilder url = new StringBuilder();
            url.append("https://api.weixin.qq.com/sns/oauth2/access_token?");
            url.append("appid=" + WeiXinConstant.AppId);
            url.append("&secret=" + WeiXinConstant.AppSecret);
            //这是微信回调给你的code
            url.append("&code=" + code);
            url.append("&grant_type=authorization_code");
            JSONObject jsonObject = doGetJson(url.toString());
            //1.获取微信用户的openid
            String openid = jsonObject.getString("openid");

            //2.获取获取access_token
            String access_token = jsonObject.getString("access_token");
            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
                    + "&lang=zh_CN";
            //3.获取微信用户信息
            JSONObject userInfo = doGetJson(infoUrl);
            //至此拿到了微信用户的所有信息,剩下的就是业务逻辑处理部分了
            //去数据库查询有没有这个 openid
            Customer user = customerService.getOne(new QueryWrapper<Customer>().lambda().eq(Customer::getOpenid, openid));
            if (user == null) {
                user = new Customer();
                user.setOpenid(openid);
                user.setNickname((String) userInfo.get("nickname"));
                user.setSex((Integer) userInfo.get("sex"));
                user.setHeadimgurl((String) userInfo.get("headimgurl"));
                user.setCountry((String) userInfo.get("country"));
                user.setProvince((String) userInfo.get("province"));
                user.setCity((String) userInfo.get("city"));
                user.setUnionid((String) userInfo.get("unionid"));
                user.setCreateTime(LocalDateTime.now());
                customerService.save(user);
            }
//            return new FebsResponse().success().put("user",user);
//            return "redirect:http://www.baidu.com";
//            return new ModelAndView("http://machaowei.utools.club?openId="+openid);
            response.sendRedirect("http://chanwu.macw.cc/?openId="+openid);
//            response.sendRedirect(url1+"?openId="+openid);
        } else {
            logger.debug("code获取失败！====" + code);
//            return new FebsResponse().fail().message("code获取失败！="+ code);
        }
//        return "redirect:http://www.baidu.com";
//        return new ModelAndView("http://machaowei.utools.club");
    }

    @RequestMapping("/getCustomer")
    @ResponseBody
    public FebsResponse getCustomer(String openId){
        Customer customer = customerService.getOne(new QueryWrapper<Customer>().lambda()
                .eq(Customer::getOpenid, openId));
        FebsResponse response = new FebsResponse().success().put("user", customer);
        return response;
    }

    /**
     * @ Description: 发送GET请求接口
     * @ Param: [uri]
     * @ return: com.alibaba.fastjson.JSONObject
     * @ Author: 马超伟
     * @ Date: 2020/6/10
     */
    public static JSONObject doGetJson(String uri) {
        JSONObject jsonObject = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(uri);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");
                jsonObject = JSONObject.parseObject(result);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //释放链接
        get.releaseConnection();
        return jsonObject;
    }

    public static void doGet(String uri) {
        JSONObject jsonObject = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(uri);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //释放链接
        get.releaseConnection();
    }



}
